/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Helper;

import demochess.ChessController;

/**
 *
 * @author Nhattruong
 */
public class ChessMessageHandler implements MessageHandlerInterface {

    private final ChessController _controller;

    public ChessMessageHandler(ChessController controller) {
        _controller = controller;
    }

    public void HandleMessage(String message) {
        if (message != null && message.length() > 5) {
            if (message.substring(0, 5).equals("move:")) {
                try {
                    int splitPos = message.indexOf("-");
                    int from = Integer.parseInt(message.substring(5, splitPos));
                    int to = Integer.parseInt(message.substring(splitPos + 1));
                    _controller.move(from, to);
                    return;
                } catch (Exception e) {
                }
            }
            if (message.substring(0, 4).equals("cmd:")) {
                if (message.substring(4).equals("cancelrequest")) {
                    _controller.cancelRequest();
                    return;
                }
                if (message.substring(4, 14).equals("askforjoin")) {
                    _controller.receiveRequest(message.substring(15));
                    return;
                }
                if (message.substring(4, 14).equals("startmatch")) {
                    String[] info = message.substring(15).split(":");
                    _controller.startMatch(info[0], info[1], info[2].equals("firstturn"));
                    return;
                }
                if (message.substring(4).equals("giveup")) {
                    _controller.rivalGiveUp();
                    return;
                }
            } else {
                if (message.substring(0, 5).equals("uplv:")) {
                    try {
                        int splitPos1 = message.indexOf("-");
                        int splitPos2 = message.lastIndexOf("-");
                        int from = Integer.parseInt(message.substring(5, splitPos1));
                        int to = Integer.parseInt(message.substring(splitPos1 + 1, splitPos2));
                        int chessType = Integer.parseInt(message.substring(splitPos2 + 1));
                        _controller.upLevelPawn(from, to, chessType);
                        return;
                    } catch (Exception e) {
                    }
                }
            }
        }
    }

    public void LostSocket() {
        _controller.rivalGiveUp();
    }
}
